<template>
  <div
    id="quotation"
    ref="quotation"
    :tabindex="-1"
    class="max-w-40 min-w-16 bg-Quotation rounded px-2 py-1"
    contenteditable="false"
  >
    <div class="flex flex-row justify-between items-center gap-2 text-base text-fontRegular">
      <span>{{ QuotationMessage.name }} :</span>
      <span v-if="showClose" class="text-red-400 text-base cursor-pointer hover:text-blue-300" @click="Close">x</span>
    </div>
    <div class="max-w-40 min-w-16 text-sm line-clamp-1 text-fontPlaceholde">{{ QuotationMessage.content }}</div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { ChatType, IMessage } from "@/types/chat.ts";
import { useCache } from "@/store/modules/cache.ts";
import { useUser } from "@/store/modules/user.ts";
import { useChat } from "@/store/modules/chat.ts";

interface IQuotationMessage {
  name: string;
  content: string;
}

let quotation = ref();
const cache = useCache();
const user = useUser();
const chat = useChat();
const props = withDefaults(
  defineProps<{
    quotationId: string;
    showClose?: boolean;
  }>(),
  {
    showClose: true,
  },
);

const QuotationMessage = computed<IQuotationMessage>(() => {
  let messageList = chat.MessageList || [];
  let message = messageList.find((m) => m.uuid === props.quotationId);
  if (!message) return { name: "", content: "" };
  return {
    name: FindSendUserName(message),
    content: message.content,
  };
});

function FindSendUserName(message: IMessage): string {
  if (message.sendId === user.userId) return user.name;
  if (message.chatType === ChatType.group) {
    const memberList = cache.GroupMemberCache.get(message.groupId!);
    if (memberList) {
      let user = memberList.find((u) => u.id === message.sendId);
      return user?.name ?? "";
    }
  }
  return chat.ChatObject?.name ?? "";
}

function Close() {
  if (quotation.value) {
    const wrapper = quotation.value.parentElement;
    wrapper.innerHTML = "";
  }
}
</script>

<style lang="scss" scoped></style>
